// ==UserScript==
// @name         【智易智慧住】美团商家一键搬单
// @namespace    http://tampermonkey.net/
// @version      2.3
// @description  订单详情模态框使用中文显示字段，适配指定API请求结构
// @author       智易智慧住
// @match        *://me.meituan.com/*
// @match        *://eb.meituan.com/*
// @grant        none
// @downloadURL  https://gitee.com/zytampermonkey/meituan/raw/master/meituan.user.js
// @updateURL    https://gitee.com/zytampermonkey/meituan/raw/master/meituan.user.js
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 日志输出函数
    function log(msg) {
        console.log(`[美团订单脚本Log] ${new Date().toLocaleTimeString()}：${msg}`);
    }

    // 提示消息函数
    function showToast(message, isError = false) {
        // 移除已有的toast
        const existing = document.querySelector('#mt-toast');
        if (existing) existing.remove();

        const toast = document.createElement('div');
        toast.id = 'mt-toast';
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 10px 20px;
            border-radius: 4px;
            color: white;
            background: ${isError ? '#f5222d' : '#52c41a'};
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            z-index: 9999999;
            transition: opacity 0.3s;
            font-size: 14px;
        `;
        toast.textContent = message;
        document.body.appendChild(toast);

        // 3秒后自动消失
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 字段中英文映射表
    const fieldMapping = {
        // 基础信息
        'arriveTime': '入住时间',
        'departureTime': '离店时间',
        'night': '入住晚数',
        'orderId': '订单号',
        'hotelName': '酒店名称',
        'createTime': '下单时间',
        'price': '订单价格(底价)',
        'roomPriceOta': '卖价',

        // 客户信息
        'name': '顾客姓名',

        // 房型信息
        'roomTypeId': '系统房型ID',
        'roomTypeName': '房型名称',
        'count': '房间数量',
        'cancelDeadline': '取消截止时间',
        'state': '订单状态',

        // 辅助字段
        'OTA房型标识': 'OTA房型标识',
        '系统房型名称': '系统房型名称'
    };

    // 显示订单详情模态框（中文显示）
    function showOrderDetail(info) {
        // 移除已有的详情面板
        const existing = document.querySelector('#mt-order-detail');
        if (existing) existing.remove();

        const detailPanel = document.createElement('div');
        detailPanel.id = 'mt-order-detail';
        detailPanel.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 500px;
            max-width: 90vw;
            max-height: 80vh;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            padding: 20px;
            z-index: 1000001;
            overflow-y: auto;
        `;

        // 生成详情HTML（使用中文显示）
        let detailHtml = '<h3 style="margin-top:0;border-bottom:1px solid #eee;padding-bottom:10px;">订单详情</h3>';
        Object.entries(info).forEach(([key, value]) => {
            // 跳过不需要显示的字段
            if (key === 'appId' || key === 'appSecret') return;

            // 获取中文标签，默认使用原key
            const chineseLabel = fieldMapping[key] || key;

            detailHtml += `
                <div style="margin-bottom:10px;padding:5px 0;border-bottom:1px dashed #f0f0f0;">
                    <strong style="display:inline-block;width:120px;color:#666;">${chineseLabel}：</strong>
                    <span>${value !== null && value !== undefined ? value : '未获取'}</span>
                </div>
            `;
        });

        // 添加操作按钮
        detailHtml += `
            <div style="text-align:center;margin-top:20px;">
                <button id="mt-copy-detail" style="margin-right:10px;padding:6px 16px;background:#1890ff;color:white;border:none;border-radius:4px;cursor:pointer;">
                    复制信息
                </button>
                <button id="mt-close-detail" style="padding:6px 16px;background:#2f54eb;color:white;border:none;border-radius:4px;cursor:pointer;">
                    关闭
                </button>
            </div>
        `;

        detailPanel.innerHTML = detailHtml;
        document.body.appendChild(detailPanel);

        // 添加遮罩层
        const overlay = document.createElement('div');
        overlay.id = 'mt-detail-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 1000000;
        `;
        document.body.appendChild(overlay);

        // 复制信息功能（保留原字段名以便技术人员使用）
        document.querySelector('#mt-copy-detail').addEventListener('click', () => {
            // 复制时使用中文标签
            const text = Object.entries(info).map(([k, v]) => {
                if (k === 'appId' || k === 'appSecret') return '';
                return `${fieldMapping[k] || k}：${v}`;
            }).filter(line => line).join('\n');

            navigator.clipboard.writeText(text).then(() => {
                showToast('信息已复制到剪贴板');
            }).catch(err => {
                showToast('复制失败，请手动复制', true);
                log('复制失败:', err);
            });
        });

        // 关闭事件
        document.querySelector('#mt-close-detail').addEventListener('click', () => {
            detailPanel.remove();
            overlay.remove();
        });

        // 点击遮罩关闭
        overlay.addEventListener('click', () => {
            detailPanel.remove();
            overlay.remove();
        });
    }

    //---------------------
    // 房型管理相关功能
    //---------------------

    // 获取房型列表 - 适配实际接口返回格式
    async function getRoomTypes() {
        const appId = localStorage.getItem('mt_appId');
        const appSecret = localStorage.getItem('mt_appSecret');

        if (!appId || !appSecret) {
            showToast('请先配置appId和appSecret', true);
            return null;
        }

        try {
            const response = await fetch('https://newpms.kingint.com/kingint/onclick/v1/4/getRoomType', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    appId: appId,
                    appSecret: appSecret
                })
            });

            if (!response.ok) {
                throw new Error(`请求失败: ${response.status}`);
            }

            const result = await response.json();

            // 适配接口返回：{success, code, message, data:[]}
            if (result && result.success && result.code === 200000 && Array.isArray(result.data)) {
                const roomTypes = result.data.map(item => ({
                    id: item.id,
                    name: item.roomTypeName
                }));

                localStorage.setItem('mt_roomTypes', JSON.stringify(roomTypes));
                log(`成功获取并保存${roomTypes.length}个房型数据`);

                // 同步映射关系（移除已不存在的房型映射）
                syncRoomTypeMappings(roomTypes);

                return roomTypes;
            } else {
                showToast(`获取房型失败: ${result?.message || '未知错误'}`, true);
                log('房型接口返回错误:', result);
                return null;
            }
        } catch (error) {
            showToast(`获取房型失败: ${error.message}`, true);
            log('获取房型列表错误:', error);
            return null;
        }
    }

    // 保存房型映射关系
    function saveRoomTypeMappings(mappings) {
        localStorage.setItem('mt_roomTypeMappings', JSON.stringify(mappings));
    }

    // 获取房型映射关系
    function getRoomTypeMappings() {
        const mappingsStr = localStorage.getItem('mt_roomTypeMappings');
        return mappingsStr ? JSON.parse(mappingsStr) : [];
    }

    // 同步房型映射（移除无效映射）
    function syncRoomTypeMappings(newRoomTypes) {
        let mappings = getRoomTypeMappings();
        const validRoomTypeIds = newRoomTypes.map(rt => rt.id);

        // 保留仅存在于最新房型列表中的映射
        const validMappings = mappings.filter(mapping =>
            validRoomTypeIds.includes(mapping.roomTypeId)
        );

        if (mappings.length !== validMappings.length) {
            saveRoomTypeMappings(validMappings);
            log(`同步后保留${validMappings.length}条有效房型映射`);
        }

        return validMappings;
    }

    // 添加单条房型映射（供绑定弹窗使用）
    function addSingleRoomMapping(otaRoomName, roomTypeId) {
        let mappings = getRoomTypeMappings();

        // 去重：避免相同OTA标识绑定同一房型
        const existingIndex = mappings.findIndex(
            m => m.otaRoomName === otaRoomName && m.roomTypeId === roomTypeId
        );

        if (existingIndex === -1) {
            mappings.push({ otaRoomName, roomTypeId });
            saveRoomTypeMappings(mappings);
            return true;
        }
        return false;
    }

    // 显示房型管理面板（仅管理已有映射）
    function showRoomTypeManager() {
        getRoomTypes().then(roomTypes => {
            if (!roomTypes) return;

            // 移除已有的面板
            const existingPanel = document.querySelector('#mt-roomtype-panel');
            if (existingPanel) existingPanel.remove();

            const mappings = getRoomTypeMappings();
            const panel = document.createElement('div');
            panel.id = 'mt-roomtype-panel';
            panel.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 700px;
                max-width: 90vw;
                max-height: 80vh;
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                z-index: 1000001;
                overflow: hidden;
            `;

            // 面板内容（仅展示和删除已有映射）
            let panelHtml = `
                <div style="padding:16px;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center;">
                    <h3 style="margin:0;font-size:16px;color:#333;">房型映射管理</h3>
                    <button id="mt-close-roomtype" style="background:none;border:none;font-size:18px;cursor:pointer;color:#666;">&times;</button>
                </div>
                <div style="padding:16px;overflow-y:auto;max-height:calc(80vh - 100px);">
                    <p style="margin:0 0 15px;color:#666;font-size:14px;">
                        管理已有的OTA售卖房型与系统房型对应关系
                    </p>

                    <table style="width:100%;border-collapse:collapse;">
                        <thead>
                            <tr style="background:#f5f5f5;">
                                <th style="padding:10px;text-align:left;border-bottom:1px solid #eee;">OTA售卖房型标识</th>
                                <th style="padding:10px;text-align:left;border-bottom:1px solid #eee;">系统房型</th>
                                <th style="padding:10px;text-align:center;border-bottom:1px solid #eee;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            // 现有映射关系
            if (mappings.length > 0) {
                mappings.forEach((mapping, index) => {
                    const roomType = roomTypes.find(rt => rt.id === mapping.roomTypeId);
                    if (roomType) {
                        panelHtml += `
                            <tr>
                                <td style="padding:10px;border-bottom:1px solid #eee;">${mapping.otaRoomName}</td>
                                <td style="padding:10px;border-bottom:1px solid #eee;">${roomType.name} (ID: ${roomType.id})</td>
                                <td style="padding:10px;text-align:center;border-bottom:1px solid #eee;">
                                    <button class="mt-delete-mapping" data-index="${index}"
                                            style="color:#f5222d;background:none;border:none;cursor:pointer;">
                                        删除
                                    </button>
                                </td>
                            </tr>
                        `;
                    }
                });
            } else {
                panelHtml += `
                    <tr>
                        <td colspan="3" style="padding:20px;text-align:center;color:#999;border-bottom:1px solid #eee;">
                            暂无房型映射关系，请在一键搬单时绑定
                        </td>
                    </tr>
                `;
            }

            panelHtml += `
                        </tbody>
                    </table>
                </div>
                <div style="padding:12px;border-top:1px solid #eee;text-align:right;">
                    <button id="mt-refresh-roomtypes" style="margin-right:8px;padding:6px 16px;background:#f5f5f5;color:#333;border:1px solid #ddd;border-radius:4px;cursor:pointer;">
                        刷新房型
                    </button>
                    <button id="mt-close-roomtype-btn" style="padding:6px 16px;background:#2f54eb;color:#fff;border:none;border-radius:4px;cursor:pointer;">
                        关闭
                    </button>
                </div>
            `;

            panel.innerHTML = panelHtml;
            document.body.appendChild(panel);

            // 添加遮罩层
            const overlay = document.createElement('div');
            overlay.id = 'mt-roomtype-overlay';
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,0.5);
                z-index: 1000000;
            `;
            document.body.appendChild(overlay);

            // 删除映射事件
            panel.querySelectorAll('.mt-delete-mapping').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const index = parseInt(e.currentTarget.dataset.index);
                    let currentMappings = getRoomTypeMappings();
                    currentMappings.splice(index, 1);
                    saveRoomTypeMappings(currentMappings);
                    showToast('映射关系已删除');
                    showRoomTypeManager(); // 重新加载面板
                });
            });

            // 刷新房型事件
            panel.querySelector('#mt-refresh-roomtypes').addEventListener('click', () => {
                getRoomTypes().then(() => {
                    showToast('房型已刷新');
                    showRoomTypeManager(); // 重新加载面板
                });
            });

            // 关闭事件
            const closeHandlers = [
                panel.querySelector('#mt-close-roomtype'),
                panel.querySelector('#mt-close-roomtype-btn')
            ];

            closeHandlers.forEach(handler => {
                if (handler) {
                    handler.addEventListener('click', () => {
                        panel.remove();
                        overlay.remove();
                    });
                }
            });

            // 点击遮罩关闭
            overlay.addEventListener('click', () => {
                panel.remove();
                overlay.remove();
            });
        });
    }

    // 显示房型绑定弹窗（在一键搬单检测到无映射时使用）
    function showRoomBindDialog(otaRoomName, onComplete) {
        // 先获取房型数据
        getRoomTypes().then(roomTypes => {
            if (!roomTypes || roomTypes.length === 0) {
                showToast('未获取到系统房型数据，无法绑定', true);
                onComplete(false);
                return;
            }

            // 移除已有的弹窗
            const existingDialog = document.querySelector('#mt-roombind-dialog');
            if (existingDialog) existingDialog.remove();

            const dialog = document.createElement('div');
            dialog.id = 'mt-roombind-dialog';
            dialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 500px;
                max-width: 90vw;
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                z-index: 1000002;
                overflow: hidden;
            `;

            // 弹窗内容
            let dialogHtml = `
                <div style="padding:16px;border-bottom:1px solid #eee;display:flex;justify-content:space-between;align-items:center;">
                    <h3 style="margin:0;font-size:16px;color:#333;">绑定房型映射</h3>
                    <button id="mt-close-bind" style="background:none;border:none;font-size:18px;cursor:pointer;color:#666;">&times;</button>
                </div>
                <div style="padding:16px;">
                    <p style="margin:0 0 15px;color:#666;">
                        检测到 "${otaRoomName}" 尚未绑定系统房型，请选择对应房型：
                    </p>

                    <div style="margin-bottom:20px;">
                        <label style="display:block;margin-bottom:8px;font-size:14px;color:#333;">系统房型选择</label>
                        <select id="bind-roomtype-id" style="width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;font-size:14px;">
                            <option value="">-- 请选择对应的系统房型 --</option>
                            ${roomTypes.map(rt => `<option value="${rt.id}">${rt.name} (ID: ${rt.id})</option>`).join('')}
                        </select>
                    </div>
                </div>
                <div style="padding:12px;border-top:1px solid #eee;text-align:right;">
                    <button id="mt-cancel-bind" style="margin-right:8px;padding:6px 16px;background:#f5f5f5;color:#333;border:1px solid #ddd;border-radius:4px;cursor:pointer;">
                        取消
                    </button>
                    <button id="mt-confirm-bind" style="padding:6px 16px;background:#52c41a;color:#fff;border:none;border-radius:4px;cursor:pointer;">
                        确认绑定
                    </button>
                </div>
            `;

            dialog.innerHTML = dialogHtml;
            document.body.appendChild(dialog);

            // 添加遮罩层
            const overlay = document.createElement('div');
            overlay.id = 'mt-bind-overlay';
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0,0,0,0.5);
                z-index: 1000001;
            `;
            document.body.appendChild(overlay);

            // 绑定确认事件
            const confirmBtn = dialog.querySelector('#mt-confirm-bind');
            confirmBtn.addEventListener('click', () => {
                const roomTypeId = dialog.querySelector('#bind-roomtype-id').value;
                if (!roomTypeId) {
                    showToast('请选择系统房型', true);
                    return;
                }

                // 保存映射关系
                const success = addSingleRoomMapping(otaRoomName, parseInt(roomTypeId));
                dialog.remove();
                overlay.remove();

                if (success) {
                    showToast('房型绑定成功');
                    onComplete(true);
                } else {
                    showToast('绑定失败，该映射关系已存在', true);
                    onComplete(false);
                }
            });

            // 取消绑定事件
            const cancelHandlers = [
                dialog.querySelector('#mt-close-bind'),
                dialog.querySelector('#mt-cancel-bind')
            ];

            cancelHandlers.forEach(handler => {
                if (handler) {
                    handler.addEventListener('click', () => {
                        dialog.remove();
                        overlay.remove();
                        onComplete(false);
                    });
                }
            });

            // 点击遮罩关闭
            overlay.addEventListener('click', () => {
                dialog.remove();
                overlay.remove();
                onComplete(false);
            });
        });
    }

    //---------------------
    // 浮动设置按钮 + 面板
    //---------------------
    function createFloatingButton() {
        // 避免重复创建
        if (document.querySelector('#mt-setting-ball')) return;

        const ball = document.createElement('div');
        ball.id = 'mt-setting-ball';
        ball.textContent = '⚙️';
        ball.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #2f54eb;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            z-index: 999999;
            transition: all 0.3s;
        `;
        // 鼠标悬停效果
        ball.addEventListener('mouseover', () => {
            ball.style.transform = 'scale(1.1)';
        });
        ball.addEventListener('mouseout', () => {
            ball.style.transform = 'scale(1)';
        });

        document.body.appendChild(ball);

        ball.addEventListener('click', () => {
            showSettingPanel();
        });
    }

    function showSettingPanel() {
        // 移除已有的面板
        const existing = document.querySelector('#mt-setting-panel');
        if (existing) existing.remove();

        const panel = document.createElement('div');
        panel.id = 'mt-setting-panel';
        panel.style.cssText = `
            position: fixed;
            bottom: 80px;
            right: 20px;
            width: 350px;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000000;
            animation: fadeIn 0.3s;
        `;

        // 添加动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        `;
        panel.appendChild(style);

        // 获取保存的配置
        const savedAppId = localStorage.getItem('mt_appId') || '';
        const savedAppSecret = localStorage.getItem('mt_appSecret') || '';
        const savedApiUrl = localStorage.getItem('mt_apiUrl') || '';

        panel.innerHTML += `
            <h3 style="margin:0 0 15px;font-size:16px;color:#333;">系统配置</h3>
            <label style="display:block;margin-bottom:12px;">
                <span style="display:block;margin-bottom:4px;font-size:14px;color:#666;">API地址：</span>
                <input type="text" id="mt-apiUrl" value="${savedApiUrl}" placeholder="例如：https://api.example.com/order"
                       style="width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;font-size:14px;">
            </label>
            <label style="display:block;margin-bottom:12px;">
                <span style="display:block;margin-bottom:4px;font-size:14px;color:#666;">appId：</span>
                <input type="text" id="mt-appId" value="${savedAppId}"
                       style="width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;font-size:14px;">
            </label>
            <label style="display:block;margin-bottom:15px;">
                <span style="display:block;margin-bottom:4px;font-size:14px;color:#666;">appSecret：</span>
                <input type="text" id="mt-appSecret" value="${savedAppSecret}"
                       style="width:100%;padding:8px;border:1px solid #ccc;border-radius:4px;font-size:14px;">
            </label>

            <div style="margin-bottom:15px;padding-top:10px;border-top:1px dashed #eee;">
                <button id="mt-roomtype-manager" style="width:100%;padding:8px 16px;background:#1890ff;color:#fff;border:none;border-radius:4px;cursor:pointer;transition:background 0.2s;">
                    房型映射管理
                </button>
            </div>

            <div style="text-align:right;">
                <button id="mt-save-btn" style="margin-right:8px;padding:8px 16px;background:#2f54eb;color:#fff;border:none;border-radius:4px;cursor:pointer;transition:background 0.2s;">保存配置</button>
                <button id="mt-cancel-btn" style="padding:8px 16px;background:#f5f5f5;color:#333;border:1px solid #ddd;border-radius:4px;cursor:pointer;transition:all 0.2s;">取消</button>
            </div>
        `;

        document.body.appendChild(panel);

        // 房型管理按钮事件
        const roomTypeBtn = panel.querySelector('#mt-roomtype-manager');
        roomTypeBtn.addEventListener('mouseover', () => {
            roomTypeBtn.style.background = '#096dd9';
        });
        roomTypeBtn.addEventListener('mouseout', () => {
            roomTypeBtn.style.background = '#1890ff';
        });
        roomTypeBtn.addEventListener('click', () => {
            panel.remove();
            showRoomTypeManager();
        });

        // 保存按钮事件
        const saveBtn = panel.querySelector('#mt-save-btn');
        saveBtn.addEventListener('mouseover', () => {
            saveBtn.style.background = '#1d4ed8';
        });
        saveBtn.addEventListener('mouseout', () => {
            saveBtn.style.background = '#2f54eb';
        });
        saveBtn.addEventListener('click', () => {
            const appId = panel.querySelector('#mt-appId').value.trim();
            const appSecret = panel.querySelector('#mt-appSecret').value.trim();
            const apiUrl = panel.querySelector('#mt-apiUrl').value.trim();

            // 简单验证
            if (!apiUrl) {
                showToast('请填写API地址', true);
                return;
            }

            localStorage.setItem('mt_appId', appId);
            localStorage.setItem('mt_appSecret', appSecret);
            localStorage.setItem('mt_apiUrl', apiUrl);

            // 保存后尝试获取房型列表
            getRoomTypes();

            showToast('配置保存成功！');
            panel.remove();
        });

        // 取消按钮事件
        panel.querySelector('#mt-cancel-btn').addEventListener('click', () => {
            panel.remove();
        });
    }

    // 验证是否为目标订单表格
    function isTargetOrderTable(table) {
        if (!table) return false;
        if (!table.classList.contains('order-eb-table')) return false;

        const ths = table.querySelectorAll('thead th');
        if (ths.length < 5) return false;

        const headers = Array.from(ths).map(th => th.textContent.trim());
        const required = ['房型','入住/离店','价格','顾客','状态'];
        return required.every(h => headers.includes(h));
    }

    // 解析入住信息
    function parseStayInfo(str) {
        // 增强日期匹配，支持包含年份的格式
        const datePattern = /\d{4}-\d{2}-\d{2}|\d{2}-\d{2}/g;
        const nightPattern = /(\d+)晚/;

        const dates = str.match(datePattern);
        const nightMatch = str.match(nightPattern);

        if (dates && dates.length === 2 && nightMatch) {
            return {
                'arriveTime': dates[0],
                'departureTime': dates[1],
                'night': parseInt(nightMatch[1], 10)
            };
        }

        return {
            'arriveTime': null,
            'departureTime': null,
            'night': null
        };
    }

    // 解析房型信息
    function parseComplexRoomInfo(text) {
        if (typeof text !== 'string') {
            return {
                roomTypeName: null,
                count: null,
                cancelDeadline: null
            };
        }

        const pattern = /^(.*?)\s+(\d+)\s+间([^]*)$/;
        const match = text.match(pattern);

        if (!match) {
            // 尝试兼容其他格式
            return {
                roomTypeName: text.trim(),
                count: 1,
                cancelDeadline: null
            };
        }

        return {
            roomTypeName: match[1].trim(),
            count: parseInt(match[2], 10),
            cancelDeadline: match[3].trim() || null
        };
    }

    // 解析价格信息，支持"卖价：¥447.41 底价：¥358.81"格式
    function parsePriceInfo(text) {
        // 默认值
        let price = '0';
        let roomPriceOta = '0';
        
        if (typeof text !== 'string') {
            return { price, roomPriceOta };
        }
        
        // 匹配"卖价：¥xxx.xx 底价：¥xxx.xx"格式
        const pricePattern = /卖价：¥([\d.]+)\s+底价：¥([\d.]+)/;
        const match = text.match(pricePattern);
        
        if (match && match.length === 3) {
            // 提取卖价和底价
            roomPriceOta = match[1];
            price = match[2];
        } else {
            // 兼容旧格式，只提取数字和小数点
            const extractedPrice = text.replace(/[^\d.]/g, '');
            price = extractedPrice || '0';
            roomPriceOta = price; // 旧格式下卖价和价格相同
        }
        
        return { price, roomPriceOta };
    }

    // 提取订单信息（适配API字段要求）
    function extractOrderInfo(tbody) {
        const bar = tbody.querySelector('.order-label-container');
        const buyTimeText = tbody.querySelector('.order-booking-text span')?.textContent.trim() || '未获取';
        const detailTr = tbody.querySelector('tr:nth-child(2)');
        if (!detailTr) return { 提示: '未找到订单详情行' };

        // 提取联系电话（如果有）
        const contactInfo = detailTr.querySelector('td:nth-child(4) .order-customer-phone')?.textContent.trim() || '未获取';

        // 合并房型信息
        const roomInfo = parseComplexRoomInfo(
            detailTr.querySelector('td:first-child .order-room-info-wrapper')?.textContent.trim() || '未获取'
        );

        // 获取房型映射关系
        const mappings = getRoomTypeMappings();
        const otaRoomName = `ota售卖${roomInfo.roomTypeName}`;
        const matchedMapping = mappings.find(m => m.otaRoomName === otaRoomName);
        const roomTypes = JSON.parse(localStorage.getItem('mt_roomTypes') || '[]');
        const matchedRoomType = roomTypes.find(rt => rt.id === matchedMapping?.roomTypeId);

        // 提取价格信息，使用新的解析函数
        const priceText = detailTr.querySelector('td:nth-child(3) .order-price-wrapper')?.textContent.trim() || '未获取';
        const { price, roomPriceOta } = parsePriceInfo(priceText);

        // 提取订单状态
        const stateText = detailTr.querySelector('td:nth-child(5) .order-status-wrapper')?.textContent.trim() || '未获取';
        const state = stateText
            .replace(/\s+/g,' ')
            .replace('权益已确认','')
            .replace('超5分钟接单可能影响HOS分','')
            .trim();

        // 提取并格式化时间
        const createTimeText = buyTimeText.replace('购买时间：','').trim();
        // 确保时间格式为"YYYY-MM-DD HH:MM:SS"
        let createTime = createTimeText;
        if (!createTime.includes(':')) {
            createTime += ' 00:00:00'; // 如果没有时间部分，补充默认时间
        }

        return {
            // 基础信息
            arriveTime: parseStayInfo(detailTr.querySelector('td:nth-child(2) .order-date-wrapper')?.textContent.trim().replace(/\s+/g,' ') || '').arriveTime,
            departureTime: parseStayInfo(detailTr.querySelector('td:nth-child(2) .order-date-wrapper')?.textContent.trim().replace(/\s+/g,' ') || '').departureTime,
            night: parseStayInfo(detailTr.querySelector('td:nth-child(2) .order-date-wrapper')?.textContent.trim().replace(/\s+/g,' ') || '').night,
            orderId: bar ? bar.querySelector('span:first-child')?.textContent.replace('订单号：','').trim() : '未获取',
            hotelName: bar ? bar.querySelector('span:nth-child(2)')?.textContent.replace('酒店：','').trim() : '未获取',
            createTime: createTime,
            price: price,
            roomPriceOta: roomPriceOta,

            // 客户信息
            name: detailTr.querySelector('td:nth-child(4) .display-name')?.textContent.trim() || '未获取',

            // 房型信息
            roomTypeId: matchedMapping ? matchedMapping.roomTypeId : null,
            roomTypeName: roomInfo.roomTypeName,
            count: roomInfo.count,
            cancelDeadline: roomInfo.cancelDeadline || '',
            state: state,

            // 认证信息（从配置获取）
            appId: localStorage.getItem('mt_appId') || '',
            appSecret: localStorage.getItem('mt_appSecret') || '',

            // 辅助字段
            'OTA房型标识': otaRoomName,
            '系统房型名称': matchedRoomType ? matchedRoomType.name : '未映射'
        };
    }

    // 发送订单到API（严格遵循指定请求结构）
    async function sendOrderToAPI(orderInfo) {
        const apiUrl = localStorage.getItem('mt_apiUrl');

        // 验证配置和必要字段
        if (!apiUrl) {
            showToast('请先配置API地址', true);
            return false;
        }

        // 验证必要字段
        const requiredFields = ['arriveTime', 'departureTime', 'night', 'orderId', 'roomTypeId'];
        const missingFields = requiredFields.filter(field => !orderInfo[field]);
        if (missingFields.length > 0) {
            // 将英文字段转换为中文提示
            const missingChinese = missingFields.map(field => fieldMapping[field] || field);
            showToast(`订单信息不完整，缺少：${missingChinese.join(', ')}`, true);
            return { success: false, error: `缺少必要字段：${missingChinese.join(', ')}` };
        }

        try {
            // 构建符合API要求的请求结构
            const apiRequestData = {
                arriveTime: orderInfo.arriveTime,
                departureTime: orderInfo.departureTime,
                night: orderInfo.night,
                orderId: orderInfo.orderId,
                hotelName: orderInfo.hotelName || '',
                createTime: orderInfo.createTime || new Date().toLocaleString(),
                price: orderInfo.price || '0',
                roomPriceOta: orderInfo.roomPriceOta || '0',
                name: orderInfo.name || '',
                roomTypeId: orderInfo.roomTypeId,
                roomTypeName: orderInfo.roomTypeName || '',
                count: orderInfo.count || 1,
                cancelDeadline: orderInfo.cancelDeadline || '',
                state: orderInfo.state || '',
                appId: orderInfo.appId,
                appSecret: orderInfo.appSecret
            };

            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Request-From': 'MeituanOrderScript'
                },
                body: JSON.stringify(apiRequestData)
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`接口返回错误: ${response.status} - ${errorText}`);
            }

            const result = await response.json();
            return { success: true, data: result };
        } catch (error) {
            log('订单提交失败:', error);
            return { success: false, error: error.message };
        }
    }

    // 为订单添加操作按钮
    function addButtonToTbody(tbody) {
        if (tbody.dataset.hasCustomBtn === "1") return; // 避免重复添加

        const detailTr = tbody.querySelector('tr:nth-child(2)');
        if (!detailTr) return;

        const lastTd = detailTr.querySelector('td:last-child');
        const op = lastTd?.querySelector('.order-operation-container');
        if (!op) return;

        // 创建按钮容器
        const wrapper = document.createElement('div');
        wrapper.style.cssText = "display: flex; flex-direction: column; align-items: center;";

        // 查看详情按钮
        const viewBtn = document.createElement('button');
        viewBtn.className = 'custom-order-info-btn mtd-btn';
        viewBtn.style.cssText = "margin:5px 4px;padding:6px 12px;min-width:68px;background:#2f54eb;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:14px;transition:background 0.2s;";
        viewBtn.textContent = '查看详情';
        viewBtn.addEventListener('mouseover', () => {
            viewBtn.style.background = '#1d4ed8';
        });
        viewBtn.addEventListener('mouseout', () => {
            viewBtn.style.background = '#2f54eb';
        });
        viewBtn.addEventListener('click', () => {
            const info = extractOrderInfo(tbody);
            showOrderDetail(info);
            log('查看订单详情:', info);
        });

        // 一键搬单按钮
        const moveBtn = document.createElement('button');
        moveBtn.className = 'custom-order-move-btn mtd-btn';
        moveBtn.style.cssText = "margin:5px 4px;padding:6px 12px;min-width:68px;background:#1890ff;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:14px;transition:background 0.2s;";
        moveBtn.textContent = '一键搬单';
        moveBtn.addEventListener('mouseover', () => {
            moveBtn.style.background = '#096dd9';
        });
        moveBtn.addEventListener('mouseout', () => {
            moveBtn.style.background = '#1890ff';
        });
        moveBtn.addEventListener('click', async () => {
            // 显示加载状态
            moveBtn.disabled = true;
            moveBtn.textContent = '处理中...';

            try {
                let info = extractOrderInfo(tbody);
                const mappings = getRoomTypeMappings();

                // 检查是否存在房型映射
                const hasMapping = mappings.some(m => m.otaRoomName === info['OTA房型标识']);

                if (!hasMapping) {
                    // 无映射关系，显示绑定弹窗
                    log(`未找到${info['OTA房型标识']}的映射关系，需要绑定`);

                    // 使用Promise包装弹窗交互
                    const bindSuccess = await new Promise(resolve => {
                        showRoomBindDialog(info['OTA房型标识'], resolve);
                    });

                    if (!bindSuccess) {
                        showToast('已取消房型绑定，订单未提交', true);
                        return;
                    }

                    // 绑定成功后重新提取订单信息（确保roomTypeId已更新）
                    info = extractOrderInfo(tbody);
                }

                // 绑定完成或已有绑定，提交订单
                const result = await sendOrderToAPI(info);
                if (result.success) {
                    showToast('订单已成功提交！');
                    log('搬单成功:', result.data);
                } else {
                    showToast(`搬单失败: ${result.error}`, true);
                }
            } catch (error) {
                showToast(`操作失败: ${error.message}`, true);
                log('操作异常:', error);
            } finally {
                // 恢复按钮状态
                moveBtn.disabled = false;
                moveBtn.textContent = '一键搬单';
            }
        });

        wrapper.appendChild(viewBtn);
        wrapper.appendChild(moveBtn);
        op.appendChild(wrapper);

        tbody.dataset.hasCustomBtn = "1"; // 标记已添加
        log('成功为订单添加操作按钮');
    }

    // 处理订单表格
    function processOrderTable(orderTable) {
        function refreshButtons() {
            const tbodies = orderTable.querySelectorAll('tbody');
            tbodies.forEach(tb => addButtonToTbody(tb));
        }

        // 初始化
        refreshButtons();
        log(`初始化：已为${orderTable.querySelectorAll('tbody').length}个订单添加按钮`);

        // 监听表格变化，动态添加按钮
        const observer = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                if (mutation.addedNodes.length > 0) {
                    log('检测到新订单，添加按钮');
                    refreshButtons();
                }
            });
        });

        observer.observe(orderTable, { childList: true, subtree: true });
        log('已启动订单表格监听');

        // 兜底定时检测
        setInterval(() => {
            if (!document.body.contains(orderTable)) {
                log('订单表格已被移除，停止监听');
                observer.disconnect();
                initInIframe(); // 重新启动检测
            } else {
                refreshButtons();
            }
        }, 5000);
    }

    // 在iframe中初始化
    function initInIframe() {
        log('脚本运行在iframe内，等待订单表格加载...');
        const timer = setInterval(()=>{
            const tables = document.querySelectorAll('table');
            for (const t of tables) {
                if (isTargetOrderTable(t)) {
                    clearInterval(timer);
                    log('找到目标订单表格');
                    processOrderTable(t);
                    return;
                }
            }
        }, 800);
    }

    // 主程序入口
    function init() {
        log('脚本开始初始化');

        // 初始化时获取房型列表
        getRoomTypes();

        if (location.host.includes('eb.meituan.com')) {
            createFloatingButton();
            initInIframe();
        } else if (location.host.includes('me.meituan.com')) {
            log('脚本运行在主页面');


            // 检测是否包含iframe，尝试在iframe中初始化
            setTimeout(() => {
                const iframes = document.querySelectorAll('iframe');
                iframes.forEach(iframe => {
                    try {
                        if (iframe.contentWindow.location.host.includes('eb.meituan.com')) {
                            log('找到订单iframe，尝试初始化');
                            iframe.contentWindow.addEventListener('load', () => {
                                initInIframe.call(iframe.contentWindow);
                            });
                        }
                    } catch (e) {
                        log('iframe访问受限:', e);
                    }
                });
            }, 2000);
        }

        log('脚本初始化完成');
    }

    // 启动脚本
    init();
})();
